const Database=require('better-sqlite3')
const path=require('path')
const db=new Database(path.join(__dirname,'app.db'))
const jwt=require('jsonwebtoken')
const jwtConfig=require('../config/jwt')

function verifyUsers(login_name,password) {
  try{
    const row=db.prepare('select * from users where login_name = ? and password = ?').get(login_name,password)
    if(row){
      const token=jwt.sign(
        {id:row.id,login_name:row.login_name},
        jwtConfig.secret,{expiresIn:jwtConfig.expiresIn})
      return {
        status:1,
        message:'登录成功',
        data:{
          id:row.id,
          login_name:row.login_name,
          token:token
        }
      }
    }else{
      return {status:0,message:'用户名或密码错误'}
    }
  }catch(err){
    return {status:0,message:err.message};
  }
}

function addUsers(login_name,password) {
  try{  
    const existingRow=db.prepare('select * from users where login_name = ?').get(login_name)
    if(existingRow){
      return {status:0,message:'用户名已存在'}
    }
    db.prepare('insert into users (login_name,password) values (?,?)').run(login_name,password);
    return {status:1,message:'注册成功'};
  }catch(err){
    return {status:0,message:err.message};
    }
}


module.exports = {
  verifyUsers,
  addUsers
};
